<template>
  <a-card :bordered="false">
    <div class="card-title">{{ $route.meta.title }}</div>
    <div class="table-operator">
      <!-- 搜索板块 -->
      <a-row class="row-item-search">
        <a-form class="search-form" :form="searchForm" layout="inline" @submit="handleSearch">
          <a-form-item label="文件名称">
            <a-input v-decorator="['name']" placeholder="请输入文件名称"/>
          </a-form-item>
          <a-form-item label="文件目录">
            <a-tree-select
                v-decorator="['directoryId']"
                treeDefaultExpandAll
                allowClear
                :treeData="directorListTreeSelect"
                :dropdownStyle="{ maxHeight: '500px', overflow: 'auto' }"
                placeholder="请选择文件目录"
            ></a-tree-select>
          </a-form-item>
          <a-form-item class="search-btn">
            <a-button type="primary" icon="search" html-type="submit">搜索</a-button>
          </a-form-item>
          <a-form-item class="search-btn">
            <a-button @click="handleReset">重置</a-button>
          </a-form-item>
        </a-form>
      </a-row>
      <!-- 操作板块 -->
      <div class="row-item-tab clearfix">
        <div class="tab-list fl-l">
          <a-radio-group :defaultValue="queryParam.fileType" @change="handleTabs">
            <a-radio-button :value="''">全部</a-radio-button>
            <a-radio-button
                v-for="(item, index) in FileTypeEnum.data"
                :key="index"
                :value="item.key"
            >{{ item.name }}
            </a-radio-button>
          </a-radio-group>
        </div>
        <div v-if="selectedRowKeys.length" class="button-group">
          <a-button-group>
            <a-button icon="swap" @click="handleBatchMove">移动</a-button>
            <a-button icon="delete" @click="handleBatchDelete">删除</a-button>
          </a-button-group>
        </div>
      </div>
    </div>
    <!-- 列表内容 -->
    <s-table
        ref="table"
        rowKey="id"
        :loading="isLoading"
        :columns="columns"
        :data="loadData"
        :rowSelection="rowSelection"
        :pageSize="15"
        :scroll="{ x: 1300 }"
    >
      <!-- 文件预览 -->
      <template v-slot:cdnUrl="text, item">
        <div class="preview-box">
          <a :href="item.cdnUrl" target="_blank">
            <img :src="text"/>
          </a>
        </div>
      </template>
      <!-- 文件名称 -->
      <template v-slot:name="text">
        <p class="oneline-hide">{{ text }}</p>
      </template>
      <!-- 文件类型 -->
      <template v-slot:fileType="text">
        <a-tag>{{ FileTypeEnum[text].name }}</a-tag>
      </template>
      <!-- 操作 -->
      <template v-slot:action="text, item">
        <a v-action:edit style="margin-right: 8px;" @click="handleRename(item)">重命名</a>
        <a v-action:download style="margin-right: 8px;" @click="handleDownload(item)">下载</a>
        <a v-action:delete @click="handleDelete(item)">删除</a>
      </template>
    </s-table>
    <!-- 移动目录 -->
    <MoveDirectoryForm ref="MoveDirectoryForm" :directoryList="directorListTree" @handleSubmit="handleRefresh"/>
    <!-- 编辑记录 -->
    <RenameForm ref="RenameForm" @handleSubmit="handleRefresh"/>
  </a-card>
</template>

<script>
import * as Api from '@/api/files'
import * as DirectoryApi from '@/api/files/directories'
import {STable} from '@/components'
import MoveDirectoryForm from './modules/MoveDirectoryForm'
import RenameForm from './modules/RenameForm'
import FileTypeEnum from '@/common/enum/file/FileType'
import StorageEnum from '@/common/enum/file/Storage'
import ChannelEnum from '@/common/enum/file/Channel'

export default {
  name: 'Index',
  components: {
    STable,
    MoveDirectoryForm,
    RenameForm
  },
  data() {
    return {
      // 枚举数据
      FileTypeEnum,
      StorageEnum,
      ChannelEnum,
      // 当前表单元素
      searchForm: this.$form.createForm(this),
      // 查询参数
      queryParam: {fileType: ''},
      // 正在加载
      isLoading: false,
      files: [],
      // 表头
      columns: [
        {
          title: '文件图片',
          dataIndex: 'cdnUrl',
          scopedSlots: {customRender: 'cdnUrl'}
        },
        {
          title: '文件名称',
          width: '260px',
          dataIndex: 'name',
          scopedSlots: {customRender: 'name'}
        },
        {
          title: '文件类型',
          dataIndex: 'fileType',
          scopedSlots: {customRender: 'fileType'}
        },
        {
          title: '文件大小(字节)',
          dataIndex: 'size'
        },
        {
          title: '文件后缀',
          dataIndex: 'ext'
        },
        {
          title: '上传时间',
          dataIndex: 'creationTime'
        },
        {
          title: '操作',
          dataIndex: 'action',
          fixed: 'right',
          scopedSlots: {customRender: 'action'}
        }
      ],
      selectedRowKeys: [],
      // 加载数据方法 必须为 Promise 对象
      loadData: param => {
        return Api.list({...param, ...this.queryParam})
      },
      // 文件目录列表(树状结构)
      directorListTree: [],
      // 文件目录列表(用于筛选组件)
      directorListTreeSelect: []
    }
  },
  created() {
    // 获取目录列表
    this.getDirectoryList()
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  methods: {

    // 选中项发生变化时的回调
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },

    // 切换tab
    handleTabs(e) {
      this.queryParam.fileType = e.target.value
      this.handleRefresh()
    },

    // 确认搜索
    handleSearch(e) {
      e.preventDefault()
      this.searchForm.validateFields((error, values) => {
        if (!error) {
          this.queryParam = {...this.queryParam, ...values}
          this.handleRefresh()
        }
      })
    },

    // 重置搜索表单
    handleReset() {
      this.selectedRowKeys = []
      this.searchForm.resetFields()
    },

    // 获取目录列表
    getDirectoryList() {
      this.isLoading = true
      DirectoryApi.list().then(result => {
        const {items} = result
        // 格式化目录列表
        const directorListTree = this.formatTreeData(items)
        // 记录到data
        this.directorListTree = directorListTree
        this.directorListTreeSelect = directorListTree
      }).finally(() => this.isLoading = false)
    },

    // 格式化目录列表
    formatTreeData(items) {
      const data = []
      items.forEach(item => {
        // 新的元素
        const newItem = {
          title: item.name,
          key: item.id,
          value: item.id
        }
        // 递归整理子集
        if (item.children && item.children.length) {
          newItem['children'] = this.formatTreeData(item['children'])
        }
        data.push(newItem)
      })
      return data
    },

    // 编辑记录
    handleRename(item) {
      this.$refs.RenameForm.edit(item)
    },

    // 删除记录
    handleDelete(item) {
      this.onDelete([item['id']])
    },

    // 批量删除
    handleBatchDelete() {
      this.onDelete(this.selectedRowKeys)
    },

    // 下载文件
    handleDownload(item) {
      Api.downloadToken(item.id).then(result => {
        Api.download(item.id, {token: result.token})
      })
    },

    // 执行删除
    onDelete(fileIds) {
      const that = this
      const modal = this.$confirm({
        title: '您确定要删除该文件吗?',
        content: '删除后不可恢复，请谨慎操作',
        onOk() {
          return Api.deleted(fileIds)
              .then(result => {
                that.$message.success('操作成功', 1.5)
                that.handleRefresh()
              })
              .catch(() => true)
              .finally(result => modal.destroy())
        }
      })
    },

    // 批量移动文件
    handleBatchMove() {
      this.$refs.MoveDirectoryForm.show(this.selectedRowKeys)
    },

    /**
     * 刷新列表
     * @param {Boolean} bool 强制刷新到第一页
     */
    handleRefresh(bool = true) {
      this.selectedRowKeys = []
      this.$refs.table.refresh(bool)
    }

  }
}
</script>
<style lang="less" scoped>
.ant-card-body {
  padding: 22px 29px 25px;
}

// 筛选tab
.tab-list {
  margin-right: 20px;
}

// 预览图
.preview-box {
  width: 120px;
  height: 80px;
  line-height: 80px;

  img {
    display: block;
    max-width: 100%;
    max-height: 100%;
  }
}
</style>
